<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/5
 * Time: 16:44
 */

namespace app\common\lib;
/**
 * AES 加密 解密类库
 * @by guokunsheng
 * Class Aes
 * @package app\common\lib
 */
class Aes
{
    /**
     * @param string $key 密钥
     * @return String
     */
    public function __construct()
    {
    }

    /**
     * 解密字符串
     * @param string $data 字符串
     * @param string $type app|live_app
     * @return string
     */
    public function decryptWithOpenssl($data, $type = 'app')
    {
        $config = config($type);
        return openssl_decrypt(base64_decode($data), $config['aes_method'], $config['aes_key'], OPENSSL_RAW_DATA, $config['aes_iv']);
    }

    /**
     * 加密字符串
     * @param string $data 字符串
     * @param string $type app|live_app
     * @return string
     */
    public function encryptWithOpenssl($data, $type = 'app')
    {
        $config = config($type);
//        echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
//        echo base64_encode(openssl_encrypt("123456","AES-128-CBC","1234567890123456",OPENSSL_RAW_DATA,"1234567890123456"));
//        $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, self::$iv);
//        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
        return base64_encode(openssl_encrypt($data, $config['aes_method'], $config['aes_key'], OPENSSL_RAW_DATA, $config['aes_iv']));
    }

    /**
     * 解密后数据转换成数组
     * @param $strData
     * @return array
     */
    public function strDataToArray($strData)
    {
        $resultData = [];

        if (!empty($strData))
        {
            $paramArrs = explode('&', $strData);

            foreach ($paramArrs as $paramArr)
            {
                $resultData[strstr($paramArr, '=', true)] = substr(strstr($paramArr, '='), 1);
            }
            //参数赋值
        }

        return $resultData;
    }

    function pkcs7_pad($str)
    {
        $len = mb_strlen($str, '8bit');
        $c = 16 - ($len % 16);
        $str .= str_repeat(chr($c), $c);
        return $str;
    }

}
